package com.lxr0860.lxr0860production_test.itemactivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.Utils;
import com.sdk.devicemanager.DEVICEcon;
import com.sdk.devicemanager.ICcon;

import java.util.Random;

public class PCIE_TestActivity extends Activity{


    private boolean isHight = false;
    private TextView mTestResultIO;
    private TextView mTestResultSwith;
    private TextView mTestResultSwitchOpen;
    private TextView mTestResultSwitchClose;
    private TextView mTestResultPoint;
    private boolean pointState = false;
    private boolean switchState1 = false;
    private boolean switchState2 = false;
    DEVICEcon devicEcon;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toString = "";
            if (msg.obj != null) {
                toString = msg.obj.toString();
            }


            switch (msg.what) {
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    PCIE_TestActivity.this.setResult(Contants.TEST_ITEM_PCIE, mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
                case 1001:
                    mTestResultIO.append(toString + "\n");

                    break;
                case 1002:
                    if (switchState2) {
                        mTestResultSwitchClose.setText("关闭成功");
                    }else{
                        mTestResultSwitchClose.setText("未检测到");
                    }
                    if (switchState1) {
                        mTestResultSwitchOpen.setText("打开成功");
                    }else{
                        mTestResultSwitchOpen.setText("未检测到");
                    }
                    if (toString.equals("测试成功")) {
                        if (switchState1 && switchState2) {
                            mTestResultSwith.append(toString);
                            Contants.showDailog(PCIE_TestActivity.this, "测试完成，是否保存", handler, Gravity.TOP);
                        } else {
                            mTestResultSwith.setText(toString);
                        }
                    } else {
                        mTestResultSwith.setText(toString);
                    }
                    break;
                case 1003:
                    String string = toString;
                    if (string.length() > 5) {
                        mTestResultPoint.setText(toString);
                    } else {
                        mTestResultPoint.append(toString);
                    }
                    break;
            }
        }
    };
    private TestThread_GPIO mTestThreadGPIO;
    private TestThread_switch mTestThreadSwitch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pcietest);
        devicEcon = new DEVICEcon(PCIE_TestActivity.this);
        mTestResultIO = findViewById(R.id.testResult_IO);
        mTestResultSwith = findViewById(R.id.testResult_swith);
        mTestResultSwitchClose = findViewById(R.id.testResult_switch_close);
        mTestResultSwitchOpen = findViewById(R.id.testResult_switch_open);
        mTestResultPoint = findViewById(R.id.testResult_point);
//        mTestResult.setMovementMethod(ScrollingMovementMethod.getInstance());

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        mTestThreadGPIO = new TestThread_GPIO();
        mTestThreadSwitch = new TestThread_switch();
        ICcon.getInstance().debugMode(true);
        initPoint();
    }

    private void initPoint() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
                powerOn_84();
                ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(1);
                String randData = randomHexString(256);
                ICcon.getInstance().PCI_CommandWrite(randData.length() / 2, Utils.hexToByteArr(randData), 200);
                Log.e("point_write", randData + " Len:" + randData.length() / 2);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String string = "";
                byte[] pci_commandRead = ICcon.getInstance().PCI_CommandRead(128, 200,100);
                if (pci_commandRead != null) {
                    String s = Utils.bytesToString(pci_commandRead).replace(" ", "");
                    string = string + s;
                    Log.e("point_read", s + "Len:" + s.length() / 2);
                    if (string.equals(randData)) {
                        mTestResultIO.setText("");
                        mTestThreadSwitch.start();
                        mTestThreadGPIO.start();
                    } else {
                        mTestResultIO.setText("请检查是否插入板卡！！！");
                        mTestResultIO.setTextColor(Color.RED);
                    }
                } else {
                    mTestResultIO.setTextColor(Color.RED);
                    mTestResultIO.setText("请检查是否插入板卡！！！");
                }
            }
        }).start();
    }

    @SuppressLint("SetTextI18n")
    private void setGPIO(int GPIO, int statte) {
        String type = "";
        if (statte == 0) {
            type = "拉低";
        } else {
            type = "拉高";
        }
        int gpioState = ICcon.getInstance().setExGpio(GPIO, statte);
    }

    private boolean powerOff84() {
        int powerOff = ICcon.getInstance().exPowerOff();
        if (powerOff == 0) {
//            mTestResult.setText("8.4下电成功");
            return true;
        } else {
//            mTestResult.setText("8.4下电失败");
            return false;
        }
    }

    private boolean powerOff33() {
        int powerOff = ICcon.getInstance().ex3PowerOff();
        if (powerOff == 0) {
//            mTestResult.setText("3.3下电成功");
            return true;
        } else {
//            mTestResult.setText("3.3下电失败");
            return false;
        }
    }

    private boolean powerOn_33() {
        int exPowerOn = ICcon.getInstance().ex3PowerOn();
        Log.v("iccard", "exPowerOn=======" + exPowerOn);
        if (exPowerOn == 0) {
//            mTestResult.setText("3.3上电成功");
            return true;
        } else {
//            mTestResult.setText("3.3上电失败");
            Log.e("8.4", "上电失败");
            return false;
        }
    }

    private boolean powerOn_84() {
        int exPowerOn = ICcon.getInstance().exPowerOn();
        Log.v("iccard", "exPowerOn=======" + exPowerOn);
        if (exPowerOn == 0) {
//            mTestResult.setText("8.4上电失败");
            return true;
        } else {
//            mTestResult.setText("8.4上电失败");
            Log.e("8.4", "上电失败");
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setGPIO(93, 0);
        setGPIO(94, 0);
        setGPIO(68, 0);
        isTest = false;
        mcount = 0;
        ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
        powerOff33();
        powerOff84();
    }

    private boolean isTest = true;
    private String randomHexString = "";

    class TestThread_GPIO extends Thread {
        @Override
        public void run() {
            super.run();
            Message message;
            //上电
            try {
//                message = handler.obtainMessage();
//                message.obj = "104灯闪两下常亮，8.4V、3.3V上电正常";
//                message.what = 1001;
//                handler.sendMessage(message);
                message = handler.obtainMessage();
                message.what = 1001;
                message.obj = "104灯闪，8.4V、3.3V上下电测试完成、\n" +
                        "101灯闪烁, IO94,接线柱测试完成、\n" +
                        "102灯闪烁，IO93，航空头测试完成、\n" +
                        "103灯闪烁,IO68测试完成,请检测灯状态";
                handler.sendMessage(message);

                while (isTest) {
                    IOControl();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    class TestThread_switch extends Thread {
        @Override
        public void run() {
            super.run();
            Message message;
            try {
                while (isTest) {
                    int switchStatus = ICcon.getInstance().get_switchStatus();
                    Log.e("switchStatus",switchStatus+"");

                    if (switchStatus == 11) {
                        message = handler.obtainMessage();
                        message.what = 1002;
                        message.obj = "打开 105亮";
                        switchState1 = true;
                        switchState2 = false;
                    } else {
                        message = handler.obtainMessage();
                        message.what = 1002;
                        message.obj = "关闭 105灭";
                        switchState2 = true;
                    }
                    Log.e("switchState",switchStatus+"");
                    handler.sendMessage(message);
                    if (switchState1 && switchState2) {
                        message = handler.obtainMessage();
                        message.what = 1002;
                        message.obj = "测试成功";
                        handler.sendMessage(message);
                        isTest = false;
                        return;
                    }

                    Thread.sleep(300);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void IOControl() throws InterruptedException {
        //IO 拉高
        //8.4上电
        setGPIO(93, 1);
        setGPIO(94, 1);
        setGPIO(68, 1);
        powerOn_84();
        Thread.sleep(500);

        //IO拉低
        //8.4下电
        setGPIO(93, 0);
        setGPIO(94, 0);
        setGPIO(68, 0);
        powerOff84();
        Thread.sleep(500);

        //IO 拉高
        //3.3上电
        setGPIO(93, 1);
        setGPIO(94, 1);
        setGPIO(68, 1);
        powerOn_33();

        Thread.sleep(500);
        //IO拉低
        //3.3下电
        setGPIO(93, 0);
        setGPIO(94, 0);
        setGPIO(68, 0);
        powerOff33();

    }

    private int mcount = 0;


    /**
     * 获取16进制随机数
     *
     * @param len
     * @return
     */
    public static String randomHexString(int len) {
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < len; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;
    }
}
